package com.loong.util;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

public class WordSearchUtil {

    /**
     * 使用顺序查找在给定的单词文件中查找指定单词，并返回以该单词为首的前15个单词及其释义
     *
     * @param wordToFind 要查找的单词
     * @param filePath   单词文件（words.txt）的路径
     * @return 包含以指定单词为首的前15个单词及其英文名称和中文释义的列表，每个元素是一个包含英文和中文释义的字符串数组，
     * 如果未找到指定单词或者文件中单词数量不足15个，则返回符合条件的部分单词信息
     */
    public static List<String> searchWordsInOrder(String wordToFind, String filePath) {
        HashSet<String> strings = new HashSet<>();
        List<String> result = new LinkedList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(new File(filePath)))) {
            String line;
            boolean found = false;
            while ((line = reader.readLine()) != null) {
                found = false;
                String[] parts = line.split("\t");
                if (parts[0].startsWith(wordToFind)) {
                    found = true;
                }
                if (found && strings.add(parts[0])) {
                    result.add(line);
                    if (strings.size() == 15) {
                        break;
                    }
                }
            }
        } catch (IOException e) {
            System.out.println("读取文件时出现错误: " + e.getMessage());
        }
        return result;
    }

    public static List<String> searchWordsInOrder(String wordToFind, Integer page, String filePath) {
        HashSet<String> strings = new HashSet<>();
        List<String> result = new LinkedList<>();
        int number = 0; // 统计单词数量
        try (BufferedReader reader = new BufferedReader(new FileReader(new File(filePath)))) {
            String line;
            boolean found = false;
            while ((line = reader.readLine()) != null) {
                found = false;
                String[] parts = line.split("\t");
                if (parts[0].startsWith(wordToFind)) {
                    found = true; // 找到单词
                }
                if (found && strings.add(parts[0])) { // 判断是否重复
                    number++; // 计数
                    if (number > page*15) {
                        result.add(line);
                    }
                    if (result.size() == 15) {
                        break;
                    }
                }
            }
        } catch (IOException e) {
            System.out.println("读取文件时出现错误: " + e.getMessage());
        }
        return result;
    }
}